var argvbeacons;


$(document).ready(function(){
		var url = window.location.href;
		$.ajax( {
			type : "GET",
			contentType:"application/json",
			dataType : 'json',
			url: "surroundingIbeacon",
			data: { url: url},
			async: false,
			success : function(ret) {
				var appid = ret.appid;
				var timestamp=ret.timestamp;
				var nonceStr=ret.nonceStr;
				var signature = ret.signature;
				wx.config({
				  debug: false,
				  appId: appid,// 必填，公众号的唯一标识
				  timestamp: timestamp,// 必填，生成签名的时间戳
				  nonceStr: nonceStr,// 必填，生成签名的随机串
				  signature: signature,// 必填，签名
				  jsApiList: [
				    'checkJsApi',
					'startSearchBeacons',
					'stopSearchBeacons',
					'onSearchBeacons'
				  ]
				});
					
			}
		})
		
		wx.ready(function () {
			jstartSearchBeacons()
		});
		
		wx.error(function (res) {
			alert(res.errMsg);
		});
})





function jstartSearchBeacons(){
  	console.log("开始开启")
	wx.startSearchBeacons({
   	ticket:"",
   	complete:function(res){
		 console.log(JSON.stringify(res));
		 var status = res.errMsg;
		 var message = "";
		 if(status=="startSearchBeacons:ok"){
			 message = "打开成功";
			 jonSearchBeacons()
		 }else if(status=="startSearchBeacons:already started"){
			 message = "";//上次未正常关闭
			 jstopSearchBeacons();
		 }else if(status=="startSearchBeacons:bluetooth power off"){
			 message = "蓝牙未打开";
		 }else if(status=="startSearchBeacons:location service disable"){
			 message = "地理位置服务未打开";
		 }else if(status=="startSearchBeacons:system unsupported"){
			 message = "系统不支持";
		 }
		 $("#message").html(message)
  	 }
	});
}

function setrequest(){
	beacons = argvbeacons.beacons
	var arg = JSON.stringify(argvbeacons); 
	if(beacons.length!=0){
		//ajax请求
		$.ajax({
			type: "GET",
			contentType: "application/json",
			dataType: 'json',
			url: "getsurroundingSite",
			data: {
				arg: arg
			},
			async: false,
			success: function(ret){
			}
		})
	}
	
}
function jonSearchBeacons(){
	console.log("查询周边设备")
	wx.onSearchBeacons({
		complete: function(argv){
			var onSearchBeaconsstatus = argv.errMsg;
			if (onSearchBeaconsstatus == "onSearchBeacons:ok") {
				argvbeacons = argv;
				jstopSearchBeacons()
				setrequest();
				console.log(argv)
				console.log("查询成功")
			}
		}
	})
}
function jstopSearchBeacons(){
	console.log("开始关闭")
	  	wx.stopSearchBeacons({
	  	   complete:function(res){
		   	 //回调函数
	  		 if(res.errMsg=="stopSearchBeacons:ok"){
				console.log("关闭成功")
	  		 }else{
				console.log("关闭失败")
	  		 }
	  	   }
	  	});
}
